//
// Created by francklinson on 2021/5/24.
//

/*
请你实现一个类SubrectangleQueries，它的构造函数的参数是一个 rows x cols的矩形（这里用整数矩阵表示），并支持以下两种操作：

1.updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

用newValue更新以(row1,col1)为左上角且以(row2,col2)为右下角的子矩形。
2.getValue(int row, int col)

返回矩形中坐标 (row,col) 的当前值。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/subrectangle-queries
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。*/

#include <vector>
#include <iostream>

using namespace std;

class SubrectangleQueries {
private:
    vector<vector<int>> rect;
public:
    SubrectangleQueries(vector<vector<int>> &rectangle) {
        rect = rectangle;
    }

    void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
        for (int i = row1; i <= row2; ++i) {
            for (int j = col1; j <= col2; ++j) {
                rect[i][j] = newValue;
            }
        }
    }

    int getValue(int row, int col) {
        return rect[row][col];
    }
};

class SubrectangleQueries2 {
private:
    vector<vector<int>> rectangle;
    vector<vector<int>> history;

public:
    SubrectangleQueries2(vector<vector<int>> &rectangle) : rectangle(rectangle) {

    }

    void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
        // cout << "updateSubrectangle " << row1 << " " << col1 << " " << row2 << " " << col2 << endl;
        history.push_back({row1, col1, row2, col2, newValue});
    }

    int getValue(int row, int col) {
        // cout << "getValue " << row << " " << col << endl;
        // 从历史从新到旧去找
        for (int i = history.size() - 1; i >= 0; --i) {
            if (row >= history[i][0] && row <= history[i][2] && col >= history[i][1] && col <= history[i][3]) {
                return history[i][4];
            }
        }
        return rectangle[row][col];
    }
};


/**
 * Your SubrectangleQueries object will be instantiated and called as such:
 * SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
 * obj->updateSubrectangle(row1,col1,row2,col2,newValue);
 * int param_2 = obj->getValue(row,col);
 */

int main() {
    vector<vector<int>> rectangle{{1, 2, 1},
                                  {4, 3, 4},
                                  {3, 2, 1},
                                  {1, 1, 1}};
    auto obj = new SubrectangleQueries(rectangle);
    cout << obj->getValue(0, 2) << endl;
    obj->updateSubrectangle(0, 0, 3, 2, 5);
    cout << obj->getValue(0, 2) << endl;
    cout << obj->getValue(3, 1) << endl;
    obj->updateSubrectangle(3, 0, 3, 2, 10);
    cout << obj->getValue(3, 1) << endl;
    cout << obj->getValue(0, 2) << endl;
    delete obj;
    return 0;
}